package com.canbot.u05.activity.shoppingGuide.advisory;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.customvoice.CustomDialogActivity;
import com.canbot.u05.adapter.AdvisoryAdapter;
import com.canbot.u05.bean.AdvisoryQA;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 咨询问答设置主界面
 */
public class SettingAdvisoryActivity extends BaseActivityNoTitle implements AdvisoryAdapter.AdvisoryAdapterOnclickListner {

        private static final String TAG = "SettingAdvisoryActivity";

        private final String AUDIO_SALE_DIR = PathConst.SHOPPING_GUIDE_DIR + "advisory/";

        private static final int NET_ERROR = 1;

        private Button btnAdd, btnDelete;

//        private ListView mListView;
        private RecyclerView mRecyclerView;

        private List<AdvisoryQA> mList;

        private AdvisoryAdapter adapter;

        private int currentPosition;

        private Dialog dialogLoading;

        private boolean isSuccess;

        private List<String> questions;


        private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        switch (msg.what) {
                                case NET_ERROR:
                                        ToastTools.newInstance(SettingAdvisoryActivity.this).showText(getString(R.string.network_error));
                                        break;
                        }
                }
        };

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_setting_advisory);
                Logger.e(TAG, "onCreate");
                boolean isFirst = getIntent().getBooleanExtra("isFirst", false);
//        if (isFirst){
//            MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND,AUDIO_SALE_DIR+"zxszdr_zxwd_u05_001.wav");
//        }
                isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, AUDIO_SALE_DIR + "zxszdr_zxwd_u05_001.wav");
                if (!isSuccess) {
                        ToastTools.newInstance(this).showText(getString(R.string.network_error));
                }
                setViews();
                initData();
        }

        @Override
        protected void onRestart() {
                super.onRestart();
                initData();
        }

        private void setViews() {
                btnDelete = (Button) findViewById(R.id.btn_delete);
                btnAdd = (Button) findViewById(R.id.btn_add);
                mRecyclerView = (RecyclerView) findViewById(R.id.listView);
        }

        /**
         * 获取数据源
         */
        private void initData() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                mList = new ArrayList<>();
                questions = new ArrayList<>();
                //获取数据
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.SOCKET_HOST2 + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<List<AdvisoryQA>> allAction = salesApi.getAllAdvisoryQA();

                allAction.enqueue(new Callback<List<AdvisoryQA>>() {
                        @Override
                        public void onResponse(Call<List<AdvisoryQA>> call, Response<List<AdvisoryQA>> response) {
                                Message message = Message.obtain();
                                if (response.body() != null) {
                                        Logger.e(TAG, "所有问答数据" + response.body().toString());
                                        List<AdvisoryQA> infos = response.body();
                                        mList.addAll(infos);
                                        for (int i = 0; i < infos.size(); i++) {
                                             questions.add(infos.get(i).getQuestion());
                                        }
                                        //设置适配
                                        setAdapter();
                                }
                                else {
//                    handler.sendMessage(message);
                                }
                                LoadingDialogUtils.closeDialog(dialogLoading);
                        }

                        @Override
                        public void onFailure(Call<List<AdvisoryQA>> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                mHandler.sendEmptyMessage(NET_ERROR);
                        }
                });
        }

        private void setAdapter() {
                mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                adapter = new AdvisoryAdapter(this, mList,mRecyclerView);
                mRecyclerView.setAdapter(adapter);
                adapter.setListener(this);

                DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this,LinearLayoutManager.VERTICAL);
                dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.shape_custom_divider));
                mRecyclerView.addItemDecoration(dividerItemDecoration);
        }

        @Override
        public void editQue() {
                //编辑问题

                Intent intent = new Intent(this, SettingQuestionActivity.class);
                String js = JSON.toJSONString(mList.get(currentPosition));
                intent.putExtra("data", js);
                Logger.e(TAG, "编辑问题===" + js);
                startActivity(intent);
//        finish();
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }

        @Override
        public void editAnswer() {

                //编辑答案
                Intent intent = new Intent(this, SelectAnswerTypeActivity.class);
                String js = JSON.toJSONString(mList.get(currentPosition));
                intent.putExtra("data", js);
                intent.putExtra("isExit", true);
                intent.putExtra("path", "/uusound");
                Logger.e(TAG, "编辑答案==" + js);
                startActivity(intent);
//        finish();
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }


        @Override
        public void del() {

                String id = mList.get(currentPosition).getId();
                Logger.e(TAG, "删除操作 del()  id == " + id);
                delDataFromPad(id);
        }

        @Override
        public void showPopuwindow(int position) {
                currentPosition = position;
        }

        /**
         * 添加键
         *
         * @param view
         */
        public void add(View view) {
                //跳转设置问题界面
                Intent intent = new Intent(this, SettingQuestionActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }


        public void importData(View view) {
                Intent intent = new Intent(this, CustomDialogActivity.class);
                intent.putExtra("type",1);
                intent.putExtra("data", JSON.toJSONString(questions));
                startActivity(intent);
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }
        /**
         * 返回键
         *
         * @param view
         */
        public void back(View view) {
                finish();
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }

        /**
         * 删除胸口数据
         *
         * @param id
         */
        private void delDataFromPad(final String id) {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.delete));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.SOCKET_HOST2 + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<String> url = salesApi.delAdvisory(id + "");
                url.enqueue(new Callback<String>() {

                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                Logger.e(TAG, "删除数据返回值" + response.body());
                                if (!TextUtils.isEmpty(response.body())) {
                                        ToastTools.newInstance(SettingAdvisoryActivity.this).showText(getString(R.string.deleted_successfully));
                                        for (int i = 0; i < mList.size(); i++) {
                                                AdvisoryQA advisoryQA = mList.get(i);
                                                String advisoryQAIdd = advisoryQA.getId();
                                                if (advisoryQAIdd.equals(id)) {
                                                        mList.remove(i);
                                                        questions.remove(i);
                                                        break;
                                                }
                                        }
                                        adapter.notifyDataSetChanged();

                                }
                                else {
                                        ToastTools.newInstance(SettingAdvisoryActivity.this).showText(getString(R.string.delete_failed));
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                ToastTools.newInstance(SettingAdvisoryActivity.this).showText(getString(R.string.network_error));
                        }
                });
        }

private static final int TIMEOUT = 100;//超时时间100s

        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }
}
